//
//  CWCMapViewController.m
//  ChuanNews
//
//  Created by dllo on 16/4/14.
//  Copyright © 2016年 dllo. All rights reserved.
//
#import "BaseHeader.h"
#import "CWCMapViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
//key:bZFMQuvH3UeahDoFwy9sCsalV1D1ICpd
@interface CWCMapViewController ()<BMKMapViewDelegate,BMKGeoCodeSearchDelegate,BMKLocationServiceDelegate,BMKGeneralDelegate,BMKRouteSearchDelegate>
@property(nonatomic, retain)BMKMapView *mapView;
@property(nonatomic, retain)UIImageView *bomeImage;
@property(nonatomic, retain)UITextField * startCity;
@property(nonatomic, retain)UITextField *startAddress;
@property(nonatomic ,retain)UITextField *endCity;
@property(nonatomic, retain)UITextField *endAddress;
@property(nonatomic, retain)BMKLocationService *locationServer;
//声明地理位置搜索对象
@property(nonatomic, retain)BMKGeoCodeSearch * getCodeSearch;
//声明路线搜索服务对象
@property(nonatomic, retain)BMKRouteSearch *routeSearch;
//开始的路线检索结点
@property(nonatomic, retain)BMKPlanNode *starNode;
//结束的路线检索结点
@property(nonatomic, retain)BMKPlanNode *endNode;

@end

@implementation CWCMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    BMKMapManager *manager = [[BMKMapManager alloc]init];
    BOOL result = [manager start:@"bZFMQuvH3UeahDoFwy9sCsalV1D1ICpd" generalDelegate:(id)self];
    if (!result) {
        NSLog(@"秘钥有问题");
    }
    [self creatView ];
    self.locationServer = [[BMKLocationService alloc]init];
    self.locationServer.delegate = self;
    [_locationServer release];
    
    //创建地理位置搜索对象
    self.getCodeSearch = [[BMKGeoCodeSearch alloc]init];
    self.getCodeSearch.delegate = self;
    [_getCodeSearch release];
    
    //创建routeSearch搜索对象
    self.routeSearch = [[BMKRouteSearch alloc]init];
    self.routeSearch.delegate = self;
    [_routeSearch release];
}
-(void)creatView{
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:@"开始定位" style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    self.navigationItem.leftBarButtonItem = left;
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"关闭定位" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];
    self.navigationItem.rightBarButtonItem = right;
    self.startCity = [[UITextField alloc]initWithFrame:CGRectMake(20, 80, 100, 30)];
    self.startCity.placeholder = @"开始城市";
    [self.view addSubview:self.startCity];
    [_startAddress release];
    self.startAddress = [[UITextField alloc]initWithFrame:CGRectMake(150, 80, 100, 30)];
    self.startAddress.placeholder = @"开始地址";
    [self.view addSubview:self.startAddress];
    [_startAddress release];
    
    self.endCity = [[UITextField alloc]initWithFrame:CGRectMake(20, 120, 100, 30)];
    self.endCity.placeholder = @"目的城市";
    [self.view addSubview:self.endCity];
    [_endCity release];
    self.endAddress = [[UITextField alloc]initWithFrame:CGRectMake(150, 120, 100, 30)];
    self.endAddress.placeholder = @"目的地址";
    [self.view addSubview:self.endAddress];
    [_endAddress release];
    
    UIButton *routeSearch = [UIButton buttonWithType:UIButtonTypeSystem];
    [routeSearch setTitle:@"路线规划" forState:UIControlStateNormal];
    routeSearch.frame = CGRectMake(300, 90, 100, 30);
    [routeSearch setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [routeSearch addTarget:self action:@selector(routeSearch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:routeSearch];
    
    self.mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 150, self.view.frame.size.width, self.view.frame.size.height - 150)];
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    [_mapView release];
}
-(void)leftAction:(UIButton *)button{
    //开启定位服务操作
    [self.locationServer startUserLocationService];
    //在地图上显示用户的位置
    self.mapView.showsUserLocation = YES;
}
-(void)rightAction:(UIButton *)button{
    //关闭定位服务
    [self.locationServer stopUserLocationService];
    //设置地图不显示用户的位置
    self.mapView.showsUserLocation = NO;
    //删除我们添加的标注对象
    [self.mapView removeAnnotation:[self.mapView.annotations firstObject]];
    NSLog(@"dasd");
}

-(void)routeSearch:(UIButton *)button{
    //完成正向地理编码
    //创建地理编码选项对象
    BMKGeoCodeSearchOption * geoSearchOption = [[BMKGeoCodeSearchOption alloc]init];
    //给想进行正向地理位置编码的位置赋值
    geoSearchOption.city = self.startCity.text;
    geoSearchOption.address = self.startAddress.text;
    //执行地理位置编码
    [self.getCodeSearch geoCode:geoSearchOption];
    
}

#pragma mark- 定位的代理方法
//开始定位
-(void)willStartLocatingUser{
    NSLog(@"开始定位");
}
//定位失败
-(void)didFailToLocateUserWithError:(NSError *)error{
    NSLog(@"定位失败%@",error);
}
//定位成功,再次定位的方法
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    //地理反编码
    //创建反向地理编码选项对象
    BMKReverseGeoCodeOption *reverseOption = [[BMKReverseGeoCodeOption alloc]init];
    //给反向地理编码选项的坐标点赋值
    reverseOption.reverseGeoPoint = userLocation.location.coordinate ;
    //执行反向地理编码操作
    [self.getCodeSearch reverseGeoCode:reverseOption];
    [reverseOption release];
    
    
    
    
}

#pragma mark - BMKGeoCodeSearch 的代理方法
//反向的地理位置编码回调方法
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    //插入大头针
    //定义大头针标注
    BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc]init];
    //设置标注的位置坐标
    annotation.coordinate = result.location;
    //大头针显示的地址
    annotation.title = result.address;
    //添加到地图
    [self.mapView addAnnotation:annotation];
    [annotation release];
    //使地图显示该位置
    [self.mapView setCenterCoordinate:result.location animated:YES];
}
//正向的地理位置编码回调方法
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if ([result.address isEqualToString:self.startAddress.text]) {
        //说明当前编码的对象是开始结点
        self.starNode = [[BMKPlanNode alloc]init];
        //给结点坐标位置赋值
        self.starNode.pt = result.location;
        [_starNode release];
        //发起对目标结点的地理编码
        BMKGeoCodeSearchOption *geoOption = [[BMKGeoCodeSearchOption alloc]init];
        geoOption.city = self.endCity.text;
        geoOption.address = self.endAddress.text;
        //执行正向编码
        [self.getCodeSearch geoCode:geoOption];
        [geoOption release];
        self.endNode = nil;
        
    }else{
        self.endNode = [[BMKPlanNode alloc]init];
        self.endNode.pt = result.location;
        [_endNode release];
        if (self.starNode != nil && self.endNode != nil) {
            //开始路线规划
            //创建自驾路线规划
            BMKDrivingRoutePlanOption *drivingRoute = [[BMKDrivingRoutePlanOption alloc]init];
            drivingRoute.from = self.starNode;
            drivingRoute.to = self.endNode;
            //[drivingRoute release];
            //让路线搜索服务对象搜索路线
            [self.routeSearch drivingSearch:drivingRoute];
        }
        
    }
}
//获取到自驾路线的回调方法
- (void)onGetDrivingRouteResult:(BMKRouteSearch *)searcher result:(BMKDrivingRouteResult *)result errorCode:(BMKSearchErrorCode)error{
    //删除原来的覆盖物
    NSArray *array = [NSArray arrayWithArray:self.mapView.annotations];
    [self.mapView removeAnnotations:array];
    //删除overlays(原来的路线轨迹)
    array = [NSArray arrayWithArray:self.mapView.overlays];
    [self.mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        //选取获取到所有路线中的一条路线
        BMKDrivingRouteLine * plan = [result.routes objectAtIndex:0];
        //计算路线方案中路段的数目
        NSUInteger size = [plan.steps count];
        //声明一个整型变量用来计算所有轨迹点的总数
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            //获取路线中的路段
            BMKDrivingStep *step = plan.steps[i];
            if ( i == 0) {
                //显示该结点是起点
                CLLocationCoordinate2D MapCoordinate = step.entrace.location;
                self.mapView .centerCoordinate = MapCoordinate;
            }
            //累计轨迹点
            planPointCounts += step.pointsCount;
        }
        //声明一个结构体数组,用来保存所有的轨迹点(每一个轨迹点都是一个结构体)
        //轨迹点结构体的名字为BMKMapPoint
        BMKMapPoint *tempPoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep *transStep = [plan.steps objectAtIndex:j];
            int k = 0;
            for (k = 0; k < transStep.pointsCount; k++) {
                //获取每个轨迹点的x,y放在数组中
                tempPoints[i].x = transStep.points[k].x;
                tempPoints[i].y = transStep.points[k].y;
                i++;
            }
        }
        //通过轨迹点绘制一条折线
        BMKPolyline *polyLine = [BMKPolyline polylineWithPoints:tempPoints count:planPointCounts];
        //添加到mapView上
        //我们想要在地图上显示轨迹,只能先添加overlay对象(类比大头针的标注),添加好之后,地图就会根据你设置的overlay显示出轨迹
        [self.mapView addOverlay:polyLine];
    }
    
}
#pragma mark - mapView的代理方法
-(BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id<BMKOverlay>)overlay{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        //创建要显示的折线
        BMKPolylineView *polyLineView = [[BMKPolylineView alloc]initWithOverlay:overlay];
        //设置折线的填充颜色
        polyLineView.fillColor = [UIColor redColor];
        //设置线条的颜色
        polyLineView.strokeColor = [UIColor redColor];
        //设置折线的宽度
        polyLineView.lineWidth = 2.0;
        return polyLineView;
    }
    return nil;
}
//回收键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

-(void)dealloc{
    self.mapView.delegate = nil;
    self.locationServer.delegate = nil;
    self.getCodeSearch.delegate = nil;
    self.routeSearch.delegate = nil;
    [_mapView release];
    [_bomeImage release];
    [_startAddress release];
    [_startCity release];
    [_endAddress release];
    [_endCity release];
    [_locationServer release];
    [_getCodeSearch release];
    [_routeSearch release];
    [_starNode release];
    [_endNode release];
    [super dealloc];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
